<template>
  <view class="index w-full min-h-screen bg-gradient-to-b from-gray-100 to-gray-300 p-4 box-border">
    <!-- 扫码按钮 -->
    <nut-button 
      class="w-full h-[120rpx] bg-red-500 text-white text-[32rpx] mb-6" 
      @click="scanBarcode"
      :loading="isScanning"
    >
      {{ isScanning ? '扫描中...' : '扫条形码' }}
    </nut-button>

    <!-- 扫描结果展示区域 -->
    <view v-if="scanResult" class="bg-white rounded-lg p-4 shadow-md">
      <view class="mb-4">
        <text class="text-[28rpx] font-bold text-gray-800 mb-2 block">扫描结果：</text>
        <view class="bg-gray-100 p-3 rounded border-l-4 border-blue-500">
          <text class="text-[26rpx] text-gray-700 break-all">{{ scanResult.result }}</text>
        </view>
      </view>

      <view class="mb-4">
        <text class="text-[28rpx] font-bold text-gray-800 mb-2 block">条形码类型：</text>
        <text class="text-[26rpx] text-blue-600">{{ scanResult.scanType }}</text>
      </view>

      <view class="mb-4">
        <text class="text-[28rpx] font-bold text-gray-800 mb-2 block">字符集：</text>
        <text class="text-[26rpx] text-green-600">{{ scanResult.charSet }}</text>
      </view>

      <!-- 扫描时拍摄的真实图片 -->
      <view v-if="scanResult.path" class="mb-4">
        <text class="text-[28rpx] font-bold text-gray-800 mb-2 block">扫描时拍摄的图片：</text>
        <view class="flex justify-center bg-gray-50 p-4 rounded">
          <image 
            :src="scanResult.path" 
            class="max-w-full h-[300rpx]" 
            mode="aspectFit"
            @error="onRealImageError"
          />
        </view>
      </view>

      <!-- 条形码图片展示 -->
      <view v-if="barcodeImage" class="mb-4">
        <text class="text-[28rpx] font-bold text-gray-800 mb-2 block">生成的条形码图片：</text>
        <view class="flex justify-center bg-gray-50 p-4 rounded">
          <image 
            :src="barcodeImage" 
            class="max-w-full h-[200rpx]" 
            mode="aspectFit"
            @error="onImageError"
          />
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="flex gap-3 mt-4">
        <nut-button 
          type="primary" 
          size="small" 
          class="flex-1"
          @click="copyResult"
        >
          复制结果
        </nut-button>
        <nut-button 
          type="default" 
          size="small" 
          class="flex-1"
          @click="generateBarcode"
        >
          生成条形码
        </nut-button>
        <nut-button 
          type="danger" 
          size="small" 
          class="flex-1"
          @click="clearResult"
        >
          清除结果
        </nut-button>
      </view>
    </view>

    <!-- 功能提示 -->
    <view v-if="!scanResult" class="mt-6 bg-blue-50 p-4 rounded-lg border-l-4 border-blue-400">
      <text class="text-[28rpx] font-bold text-blue-800 block mb-2">📱 扫码功能说明</text>
      <text class="text-[24rpx] text-blue-600 block mb-1">• 支持条形码和二维码扫描</text>
      <text class="text-[24rpx] text-blue-600 block mb-1">• 自动生成对应的图片</text>
      <text class="text-[24rpx] text-blue-600 block mb-1">• 支持复制扫描结果</text>
      <text class="text-[24rpx] text-blue-600 block">• 自动保存扫描历史</text>
    </view>

    <!-- 扫描历史 -->
    <view v-if="scanHistory.length > 0" class="mt-6">
      <view class="flex items-center justify-between mb-3">
        <text class="text-[28rpx] font-bold text-gray-800">📋 扫描历史 ({{ scanHistory.length }})</text>
        <nut-button 
          type="danger" 
          size="mini" 
          @click="clearHistory"
          class="text-[20rpx]"
        >
          清空历史
        </nut-button>
      </view>
      <view class="max-h-[600rpx] overflow-y-auto">
        <view 
          v-for="(item, index) in scanHistory" 
          :key="index"
          class="bg-white p-3 rounded-lg border border-gray-200 mb-2 active:bg-gray-50"
          @click="selectHistoryItem(item)"
        >
          <view class="flex items-center justify-between mb-1">
            <text class="text-[24rpx] text-gray-600">{{ formatTime(item.time) }}</text>
            <text class="text-[20rpx] px-2 py-1 bg-blue-100 text-blue-600 rounded">{{ item.scanType || '条形码' }}</text>
          </view>
          <text class="text-[26rpx] text-gray-800 block">{{ item.result.substring(0, 50) }}{{ item.result.length > 50 ? '...' : '' }}</text>
          <text class="text-[22rpx] text-gray-500 block mt-1">点击查看详情</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import Taro from "@tarojs/taro";

// 响应式数据
const isScanning = ref(false)
const scanResult = ref<any>(null)
const barcodeImage = ref<string>('')
const scanHistory = ref<any[]>([])

// 页面加载时获取历史记录
onMounted(() => {
  loadScanHistory()
})

// 扫描条形码
const scanBarcode = async () => {
  try {
    isScanning.value = true
    
    const res = await Taro.scanCode({
      onlyFromCamera: true, // 只允许从相机扫码
      scanType: ['barCode', 'qrCode'], // 支持条形码和二维码
    })
    
    console.log('扫描结果:', res)
    
    // 保存扫描结果
    scanResult.value = {
      result: res.result,
      scanType: res.scanType,
      charSet: res.charSet || 'UTF-8',
      path: res.path || ''
    }
    
    // 生成条形码图片
    generateBarcodeImage(res.result)
    
    // 保存到历史记录
    saveScanHistory(scanResult.value)
    
    Taro.showToast({
      title: '扫描成功',
      icon: 'success'
    })
    
  } catch (error: any) {
    console.error('扫描失败:', error)
    
    if (error.errMsg && error.errMsg.includes('cancel')) {
      Taro.showToast({
        title: '取消扫描',
        icon: 'none'
      })
    } else {
      Taro.showToast({
        title: '扫描失败',
        icon: 'error'
      })
    }
  } finally {
    isScanning.value = false
  }
}

// 生成条形码图片
const generateBarcode = () => {
  if (!scanResult.value?.result) {
    Taro.showToast({
      title: '请先扫描条形码',
      icon: 'none'
    })
    return
  }
  
  generateBarcodeImage(scanResult.value.result)
}

// 生成条形码图片（使用第三方API）
const generateBarcodeImage = (text: string) => {
  try {
    const encodedText = encodeURIComponent(text)
    
    // 根据扫描类型选择合适的图片生成API
    if (scanResult.value?.scanType === 'QR_CODE') {
      // 二维码
      barcodeImage.value = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodedText}&format=png`
    } else {
      // 条形码 - 使用barcode generator API
      barcodeImage.value = `https://barcode.tec-it.com/barcode.ashx?data=${encodedText}&code=Code128&translate-esc=true&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0`
    }
    
    console.log('生成条形码图片:', barcodeImage.value)
  } catch (error) {
    console.error('生成条形码失败:', error)
    Taro.showToast({
      title: '生成图片失败',
      icon: 'error'
    })
  }
}

// 复制扫描结果
const copyResult = () => {
  if (!scanResult.value?.result) return
  
  Taro.setClipboardData({
    data: scanResult.value.result,
    success: () => {
      Taro.showToast({
        title: '复制成功',
        icon: 'success'
      })
    },
    fail: () => {
      Taro.showToast({
        title: '复制失败',
        icon: 'error'
      })
    }
  })
}

// 清除结果
const clearResult = () => {
  scanResult.value = null
  barcodeImage.value = ''
  Taro.showToast({
    title: '已清除',
    icon: 'success'
  })
}

// 图片加载错误处理
const onImageError = () => {
  console.error('条形码图片加载失败')
  barcodeImage.value = ''
  Taro.showToast({
    title: '图片加载失败',
    icon: 'none'
  })
}

// 真实图片加载错误处理
const onRealImageError = () => {
  console.error('扫描时拍摄的图片加载失败')
  Taro.showToast({
    title: '扫描图片加载失败',
    icon: 'none'
  })
}

// 保存扫描历史
const saveScanHistory = (result: any) => {
  const historyItem = {
    ...result,
    time: Date.now()
  }
  
  scanHistory.value.unshift(historyItem)
  
  // 只保留最近20条记录
  if (scanHistory.value.length > 20) {
    scanHistory.value = scanHistory.value.slice(0, 20)
  }
  
  // 保存到本地存储
  Taro.setStorageSync('scanHistory', scanHistory.value)
}

// 加载扫描历史
const loadScanHistory = () => {
  try {
    const history = Taro.getStorageSync('scanHistory')
    if (history && Array.isArray(history)) {
      scanHistory.value = history
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 选择历史记录项
const selectHistoryItem = (item: any) => {
  scanResult.value = item
  generateBarcodeImage(item.result)
  
  Taro.showToast({
    title: '已选择历史记录',
    icon: 'success'
  })
}

// 清空扫描历史
const clearHistory = () => {
  Taro.showModal({
    title: '确认清空',
    content: '确定要清空所有扫描历史记录吗？',
    success: (res) => {
      if (res.confirm) {
        scanHistory.value = []
        Taro.removeStorageSync('scanHistory')
        Taro.showToast({
          title: '历史已清空',
          icon: 'success'
        })
      }
    }
  })
}

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString() + ' ' + date.toLocaleTimeString().slice(0, 5)
  }
}

</script>
